package org.scisaga.tetra.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

/**
 * Find MathKernel Address
 * @author XiaoGuiZi
 * TODO: Linux version is not finished.
 */
public class FindMathematicaRegistry {

	private static final String REGQUERY_UTIL = "reg query ";
	//private static final String REGSTR_TOKEN = "REG_SZ";
	private static final String EXCEL_PATH_CMD = REGQUERY_UTIL
			+ "\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wolfram Research\" /s"; // /s : 查询所有子项

	public String[] getInstallRoot() {
		try {
			Process process = Runtime.getRuntime().exec(EXCEL_PATH_CMD);
			StreamReader reader = new StreamReader(process.getInputStream());

			reader.start();
			process.waitFor();
			reader.join();
			String result = reader.getResult();
			System.out.println(result);
			int p = result.indexOf(":");
			int q = result.indexOf("Mathematica.exe");
			if (p == -1)
				return null;
			String[] back=new String[2];
			back[0]= result.substring(p -1, q).trim();
			back[1]=back[0].substring(0,16)+" (x86)"+back[0].substring(16);
			System.out.println(back[0]);
			System.out.println(back[1]);
			return back;
		} catch (Exception e) {
			return null;
		}
	}

	static class StreamReader extends Thread {
		private InputStream is;
		private StringWriter sw;

		StreamReader(InputStream is) {
			this.is = is;
			sw = new StringWriter();
		}

		public void run() {
			try {
				int c;
				while ((c = is.read()) != -1)
					sw.write(c);
			} catch (IOException e) {
			}
		}

		String getResult() {
			return sw.toString();
		}
	}
	
	static public void main(String[] argv){
		System.out.println(new FindMathematicaRegistry().getInstallRoot());
	}
}